package com.shfl.controller;

import com.alibaba.fastjson.JSON;
import com.shfl.common.ApiSimpleResultHelper;
import com.shfl.component.ToolServiceComponent;
import com.shfl.models.*;
import com.shfl.models.response.CreateOrderResponse;
import com.shfl.rect.DialogStage;
import com.shfl.rect.RectD;
import com.shfl.single.SingleUserInfo;
import com.shfl.stock.Stock;
import com.shfl.utils.AlertUtil;
import com.shfl.utils.PropertiesUtil;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.*;
import javafx.scene.control.TextArea;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.util.Callback;
import javafx.util.Duration;
import sun.misc.BASE64Decoder;

import java.awt.*;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

public class ConvertImageContorller implements Initializable {


    @FXML
    private TabPane tabPage;

    @FXML
    private Tab tab1;
    /**
     * 下拉框
     */
    @FXML
    private ComboBox<String> selectType;

    @FXML
    private TextArea content;

    @FXML
    private Button captureConversion;

    private Integer recognitionType = 1;

    //账户信息

    @FXML
    private Tab account;

    @FXML
    private TableColumn account_goodsName;
    @FXML
    private TableColumn account_endTime;
    @FXML
    private TableColumn account_residueDegree;

    @FXML
    private TableView account_table;

    //充值

    @FXML
    private Tab recharge;
    @FXML
    private TableColumn recharge_goodsName;
    @FXML
    private TableColumn recharge_goodsValue;
    @FXML
    private TableColumn recharge_payMoney;
    @FXML
    private TableColumn recharge_but;
    @FXML
    private TableColumn recharge_goodsNo;

    @FXML
    private TableView recharge_table;

    //二维码
    @FXML
    private ImageView payCode;

    //通知
    @FXML
    private TextArea inform;

    //增加初始值

    private boolean accountBoolean = true;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

        List<String> list = new ArrayList<>();
        list.add("通用");
        list.add("通用(高精度)");
//        list.add("手写文字识别");
//        list.add("身份证识别");
//        list.add("银行卡识别");
//        list.add("识别营业执照");
//        list.add("护照识别");
//        list.add("名片识别");
//        list.add("户口识别");
//        list.add("通用票据识别");
//        list.add("增值税发票识别");


        this.selectType.setItems(FXCollections.observableArrayList(list));
        this.selectType.getSelectionModel().selectFirst();
        this.selectType.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> recognitionType = selectType.getItems().indexOf(newValue.toString()) + 1);
        /**
         * 截图按钮
         */
        this.captureConversion.setOnAction(event -> {
            DialogStage dialogStage = new DialogStage(Stock.INDEX_STAGE, "图片读取中，请稍后...");
            content.setText("");
            dialogStage.activateProgressBar();
            try {
                Stock.INDEX_STAGE.setIconified(true);
                Stock.executor.execute(() -> {
                            try {
                                screenShots();
                                Platform.runLater(() -> Stock.INDEX_STAGE.setIconified(false));
                                setCaptureConversion();
                            } catch (InterruptedException e) {

                            } finally {
                                Platform.runLater(dialogStage::cancelProgressBar);
                            }
                        }

                );
//                new Thread(() -> {
//                    try {
//                        new runnAble11().run();
//                        Platform.runLater(new Runnable() {
//                            @Override
//                            public void run() {
//                                Stock.CONVERT_IMAGE_STAGE.setIconified(false);
//                            }
//                        });
//                        setCaptureConversion();
//                    } finally {
//                        Platform.runLater(new Runnable() {
//                            @Override
//                            public void run() {
//                                dialogStage.cancelProgressBar();
//                            }
//                        });
//                    }
//                }, "conversion").start();
            } catch (Exception e) {
                content.setText(e.getMessage());
            }
        });
        tab1.setOnSelectionChanged(event -> {
            if (accountBoolean) {
                Stock.executor.execute(this::getAccount);
//                new Thread(() -> {
//                    getAccount();
//                }, "account").start();
            }
            accountBoolean = false;
        });
        Stock.executor.execute(this::getGoodsInfo);
//        new Thread(() -> {
//            getGoodsInfo();
//        }, "recharge").start();

        //通知

        String informText = "";
        try {
            informText = PropertiesUtil.getProperty(Stock.proUrl, "project.affiche");
        } catch (IOException e) {
            e.printStackTrace();
        }
        inform.setText(informText + SingleUserInfo.getSingleUserInfo().getAffiche());
    }

    /**
     * 获取账户信息
     */
    public void getAccount() {

        ApiSimpleResultHelper result = new ToolServiceComponent().account();
        if (!"0000".equals(result.getResCode())) {
            AlertUtil.f_alert_informationDialog(result.getResDesc());
            return;
        }
        //获取table
        List<Map> resultList = JSON.parseArray(JSON.toJSONString(result.getData()), Map.class);
        ObservableList<AccountInfo> data
                = FXCollections.observableArrayList();
        for (Map map : resultList) {
            data.add(new AccountInfo(map.get("accountName").toString(), map.get("endTimeValue").toString(), map.get("residueDegree").toString()));
        }
        account_goodsName.setCellValueFactory(new PropertyValueFactory<>("accountName"));
        account_endTime.setCellValueFactory(new PropertyValueFactory<>("endTimeValue"));
        account_residueDegree.setCellValueFactory(new PropertyValueFactory<>("residueDegree"));
        account_table.setItems(data);
    }

    //获取商品信息
    public void getGoodsInfo() {
        ApiSimpleResultHelper result = new ToolServiceComponent().goodsInfo();
        if (!"0000".equals(result.getResCode())) {
            AlertUtil.f_alert_informationDialog(result.getResDesc());
            return;
        }
        //获取table
        Map resultMap = JSON.parseObject(JSON.toJSONString(result.getData()), Map.class);
        ObservableList<GoodsInfo> data
                = FXCollections.observableArrayList();
        //有效次数
        List<Map> validCountMapList = JSON.parseArray(JSON.toJSONString(resultMap.get("validCountList")), Map.class);
        for (Map validCountMap : validCountMapList) {
            data.add(new GoodsInfo(validCountMap.get("goodsName").toString(), Integer.valueOf(validCountMap.get("goodsId").toString()), validCountMap.get("useCount").toString() + "（次）", validCountMap.get("payMoney").toString()));
        }
        //有效期
        List<Map> validityMapList = JSON.parseArray(JSON.toJSONString(resultMap.get("validityList")), Map.class);
        for (Map validityMap : validityMapList) {
            data.add(new GoodsInfo(validityMap.get("goodsName").toString(), Integer.valueOf(validityMap.get("goodsId").toString()), validityMap.get("useCount").toString() + "（天）", validityMap.get("payMoney").toString()));
        }
        recharge_goodsName.setCellValueFactory(new PropertyValueFactory<>("goodsName"));
        recharge_goodsValue.setCellValueFactory(new PropertyValueFactory<>("useCount"));
        recharge_payMoney.setCellValueFactory(new PropertyValueFactory<>("payMoney"));
        recharge_goodsNo.setCellValueFactory(new PropertyValueFactory<>("goodsId"));

        //操作按钮
        Callback<TableColumn<GoodsInfo, String>, TableCell<GoodsInfo, String>> cellFactory
                = new Callback<TableColumn<GoodsInfo, String>, TableCell<GoodsInfo, String>>() {
            @Override
            public TableCell call(final TableColumn<GoodsInfo, String> param) {
                final TableCell<GoodsInfo, String> cell = new TableCell<GoodsInfo, String>() {

                    final Button btn = new Button("充值");

                    @Override
                    public void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty) {
                            setGraphic(null);
                            setText(null);
                        } else {
                            btn.setOnAction(event -> {
                                btn.setDisable(true);
                                //获取付款二维码
                                GoodsInfo goodsInfo = getTableView().getItems().get(getIndex());
                                createOrder(goodsInfo.getGoodsId());
                                accountBoolean = true;
                            });
                            setGraphic(btn);
                            setText(null);
                            //按钮禁用
                            final Timeline animation = new Timeline(
                                    new KeyFrame(Duration.seconds(60),
                                            new EventHandler<ActionEvent>() {
                                                @Override
                                                public void handle(ActionEvent actionEvent) {
                                                    btn.setDisable(false);
                                                }
                                            }));
                            animation.setCycleCount(1);
                            animation.play();
                        }
                    }
                };
                return cell;
            }
        };
        recharge_but.setCellFactory(cellFactory);
        recharge_table.setItems(data);
    }


    /**
     * 获取图片的值
     */
    public void setCaptureConversion() {
        if (Stock.rd == null || Stock.rd.getResults() == null) {
            content.setText("请选择图片！");
            return;
        }
        ImageToTextInfo info = new ImageToTextInfo();
        info.setInputStream(Stock.rd.getResults());
        info.setRecognitionType(recognitionType);
        ApiSimpleResultHelper result = new ToolServiceComponent().auth(info);
        if (!"0000".equals(result.getResCode())) {
            content.setText(result.getResDesc());
            return;
        }
        accountBoolean = true;
        content.setText(new ResultInfo(recognitionType, JSON.toJSONString(result.getData())).getResult());
    }


    protected void createOrder(Integer goodsId) {
        CreateOrderInfo createOrderInfo = new CreateOrderInfo();
        createOrderInfo.setGoodsId(goodsId);
        ApiSimpleResultHelper result = new ToolServiceComponent().createOrder(createOrderInfo);
        if (!"0000".equals(result.getResCode())) {
            AlertUtil.f_alert_informationDialog(result.getResDesc());
            return;
        }
        CreateOrderResponse createOrderResponse = JSON.parseObject(JSON.toJSONString(result.getData()), CreateOrderResponse.class);
        payCode.setImage(new Image(getInputStreamByBease64(createOrderResponse.getBase64())));

    }

    /**
     * 根据base64的图片获取输入流
     *
     * @param val
     * @return
     */
    public InputStream getInputStreamByBease64(String val) {
        val = val.replaceAll("data:image/png;base64,", "");
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] imageByte = null;
        try {
            imageByte = decoder.decodeBuffer(val);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ByteArrayInputStream(imageByte);
    }

    /**
     * 识别本地图片的文字
     *
     * @param path 本地图片地址
     * @return 识别结果，为json格式
     * @throws URISyntaxException URI打开异常
     * @throws IOException        io流异常
     */
    public static InputStream getInputStream(String path) throws FileNotFoundException {
        File file = new File(path);
        if (!file.exists()) {
            throw new NullPointerException("图片不存在");
        }
        return new FileInputStream(path);
    }

    /**
     * 截取屏幕
     */
    public void screenShots() throws InterruptedException {
        synchronized (Stock.obj) {
            try {
                Thread.sleep(10L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Stock.rd = new RectD();
            RectD rd = Stock.rd;
            GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment()
                    .getDefaultScreenDevice();
            gd.setFullScreenWindow(rd);
            Stock.obj.wait();
            rd.getDefaultCloseOperation();
        }

    }
}
